package com.wifeacountbook;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.wifeacountbook.util.AcountDBOpenHelper;
import com.wifeacountbook.util.AcountKeeper.ConsumeDetail;

public class AcountStaticer extends Activity implements OnClickListener {
	private static final String TAG = "AcountStaticer";
	private Date curtMon = null;
	private ListView mList = null;
	private ListAdapter adapter = null;
	private TextView mTotalDesc = null;
	private ImageButton nxtBtn = null;
	private ImageButton preBtn = null;
	private TextView mDescTv = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		curtMon = new Date();
		setContentView(R.layout.consume_static_layout);
		mList = (ListView) findViewById(R.id.list_static);
		mTotalDesc = (TextView) findViewById(R.id.totaldesc);
		nxtBtn = (ImageButton) findViewById(R.id.btn_next);
		preBtn = (ImageButton) findViewById(R.id.btn_pre);
		mDescTv = (TextView) findViewById(R.id.textview_desc);
		
	}

	@Override
	protected void onResume() {// load data for the list view.
		super.onResume();

		ArrayList<HashMap<String, String>> adptorList = updateCursor(curtMon);
		adapter = new SimpleAdapter(this, adptorList,
				R.layout.consume_static_layout_listitem, new String[] {
						"payType", "total", "Persent" }, new int[] {
						R.id.textView1, R.id.textView2, R.id.textView3 });

		mList.setAdapter(adapter);
		int total = 0;
		for (HashMap<String, String> mp : adptorList) {
			String tTotal = mp.get("total");
			if (!TextUtils.isEmpty(tTotal) && TextUtils.isDigitsOnly(tTotal)) {
				total += Integer.parseInt(tTotal);
			}
		}

		// set total static.
		String sTotalDesc = getString(R.string.str_total_desc);
		mTotalDesc.setText(sTotalDesc + "  " + total + "_");
		nxtBtn.setOnClickListener(this);
		preBtn.setOnClickListener(this);
		
		setDesc();
	}

	private void setDesc() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		String mon = sdf.format(curtMon);
		mDescTv.setText(mon + getString(R.string.str_static_desc));
	}

	// TODO 将统计结果保存到统计数据表中。不需要每次查询都进行统计。
	private ArrayList<HashMap<String, String>> updateCursor(Date date) {

		Date tdate = new Date();
		int offYear = date.getYear() - tdate.getYear();
		int offMon = date.getMonth() - tdate.getMonth();
		int offMonEnd = offMon + 1;

		String soffYear = offYear >= 0 ? "+" + offYear : "" + offYear;
		String soffMon = offMon >= 0 ? "+" + offMon : "" + offMon;
		String soffMonEnd = offMonEnd >= 0 ? "+" + offMonEnd : "" + offMonEnd;

		String startDate = "date('now','start of month','" + soffYear
				+ " year','" + soffMon + " month')";
		String endDate = "date('now','start of month','" + offYear + " year','"
				+ soffMonEnd + " month','-1 day')";

		String selection = ConsumeDetail.CONSUMETIME + ">= " + startDate
				+ " and " + ConsumeDetail.CONSUMETIME + "<= " + endDate;
		String sql = "select payType,sum(money) total  from  (select * from acount_consume_info where "
				+ selection + " ) group by payType";
		Log.e(TAG, ">>>>>>>>>>>>>.sql=" + sql);
		Cursor cursor = null;
		SQLiteOpenHelper acountDBOpenHelper = null;
		SQLiteDatabase readableDatabase = null;
		ArrayList<HashMap<String, String>> adptorList = new ArrayList<HashMap<String, String>>();
		try {
			acountDBOpenHelper = new AcountDBOpenHelper(this);
			readableDatabase = acountDBOpenHelper.getReadableDatabase();
			cursor = readableDatabase.rawQuery(sql, null);
			if (cursor != null)
				Log.e(TAG, ">>>>>>>>>>>>>.count =" + cursor.getCount());

			if (cursor == null || cursor.getCount() == 0)
				return adptorList;
			int totalMoney = 0;
			while (cursor.moveToNext()) {
				totalMoney += cursor.getInt(cursor.getColumnIndex("total"));
			}
			Log.e(TAG, ">>>>>>>>>>>>>.totalMoney=" + totalMoney);
			cursor.moveToFirst();
			do {
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("payType", cursor.getString(cursor
						.getColumnIndex("payType")));
				int total = cursor.getInt(cursor.getColumnIndex("total"));
				map.put("total", cursor.getString(cursor
						.getColumnIndex("total")));
				map.put("Persent", "" + total * 100 / totalMoney + "%");
				adptorList.add(map);
			} while (cursor.moveToNext());
			return adptorList;
		} catch (Exception ex) {
			Log.e("TAG", "sql excute error:" + ex.getMessage());
			ex.printStackTrace();
		} finally {
			if (readableDatabase != null) {
				readableDatabase.close();
				readableDatabase = null;
			}
			if (acountDBOpenHelper != null) {
				acountDBOpenHelper.close();
				acountDBOpenHelper = null;
			}
			if (cursor != null) {
				cursor.close();
				cursor = null;
			}
		}

		return adptorList;
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.btn_next) {
			Calendar c = Calendar.getInstance();
			c.setTime(curtMon);
			c.add(Calendar.MONTH, 1);
			curtMon = c.getTime();
		} else if (v.getId() == R.id.btn_pre) {
			Calendar c = Calendar.getInstance();
			c.setTime(curtMon);
			c.add(Calendar.MONTH, -1);
			curtMon = c.getTime();
		}

		setDesc();
		ArrayList<HashMap<String, String>> adptorList = updateCursor(curtMon);
		adapter = new SimpleAdapter(this, adptorList,
				R.layout.consume_static_layout_listitem, new String[] {
						"payType", "total", "Persent" }, new int[] {
						R.id.textView1, R.id.textView2, R.id.textView3 });

		int total = 0;
		for (HashMap<String, String> mp : adptorList) {
			String tTotal = mp.get("total");
			if (!TextUtils.isEmpty(tTotal) && TextUtils.isDigitsOnly(tTotal)) {
				total += Integer.parseInt(tTotal);
			}
		}

		// set total static.
		String sTotalDesc = getString(R.string.str_total_desc);
		mTotalDesc.setText(sTotalDesc + "  " + total + "_");
		mList.setAdapter(adapter);
	}

}
